package com.application;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.application.base.BaseActivity;
import com.application.databinding.ActivitySqliteDeleteBinding;
import com.application.util.ARouterConstants;
import com.application.util.MySQLiteOpenHelper;
import com.application.viewmodel.SQLiteDeleteViewModel;

@Route(path = ARouterConstants.ACTIVITY_URL_SQLITE_DELETE)
public class SQLiteDeleteActivity extends BaseActivity<ActivitySqliteDeleteBinding, SQLiteDeleteViewModel> {

    @Override
    protected int initLayoutId() {
        return R.layout.activity_sqlite_delete;
    }

    @Override
    protected int initVariableId() {
        return BR.sqliteDeleteViewModel;
    }

    @Override
    protected void initData() {
        super.initData();
        binding.setActivity(this);
        observeViewModelEvents(); // 观察ViewModel事件
    }

    private void observeViewModelEvents() {
        // 显示Toast消息
        viewModel.toastMsgEvent.observe(this, msg -> {
            if (!msg.isEmpty()) {
                Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
            }
        });

        // 清空输入框
        viewModel.clearInputEvent.observe(this, shouldClear -> {
            if (shouldClear != null && shouldClear) {
                clearInputFields();
                viewModel.clearInputEvent.setValue(false); // 重置事件
            }
        });

        // 显示确认删除对话框
        viewModel.showDialogEvent.observe(this, shouldShow -> {
            if (shouldShow != null && shouldShow) {
                showDeleteConfirmDialog();
                viewModel.showDialogEvent.setValue(false); // 重置事件
            }
        });
    }

    // 显示删除确认对话框
    private void showDeleteConfirmDialog() {
        String name = viewModel.nameLiveData.getValue();
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除 " + name + " 的信息吗？此操作不可撤销。")
                .setPositiveButton("删除", (dialog, which) -> {
                    viewModel.performDelete(); // 调用ViewModel执行删除
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                })
                .show();
    }

    // 清空输入框
    private void clearInputFields() {
        viewModel.nameLiveData.setValue("");
        viewModel.numberLiveData.setValue("");
    }
}